package com.moqianfan.mcuassistant.fragment.more;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.moqianfan.mcuassistant.R;
import com.moqianfan.mcuassistant.activity.CollecActivity;
import com.moqianfan.mcuassistant.activity.LoginActivity;
import com.moqianfan.mcuassistant.activity.UserInfoActivity;
import com.moqianfan.mcuassistant.bean.User;
import com.moqianfan.mcuassistant.fragment.BaseFragment;
import com.moqianfan.mcuassistant.utils.LogUtil;
import com.moqianfan.mcuassistant.view.CircleTransform;
import com.squareup.picasso.Picasso;
import com.umeng.analytics.MobclickAgent;

import net.youmi.android.os.EarnPointsOrderList;
import net.youmi.android.os.OffersBrowserConfig;
import net.youmi.android.os.OffersManager;
import net.youmi.android.os.PointsChangeNotify;
import net.youmi.android.os.PointsEarnNotify;
import net.youmi.android.os.PointsManager;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import cn.sharesdk.onekeyshare.OnekeyShare;


/**
 * Created by Administrator on 2016/11/6.
 * 用户页面
 */

public class MineFragment extends BaseFragment {
    @BindView(R.id.txt_fav)
    TextView txtFav;
    @BindView(R.id.txt_share)
    TextView txtShare;
    @BindView(R.id.txt_comment)
    TextView txtComment;
    @BindView(R.id.image_header)
    ImageView imageHead;
    @BindView(R.id.txt_username)
    TextView txtUserName;
    @BindView(R.id.txt_score)
    TextView txtScore;
    @BindView(R.id.txt_sign)
    TextView txtSign;
    @BindView(R.id.image_sex)
    ImageView imageSex;

    private PopupWindow popupWindow;
    private String TAG = "MineFragment";

    @Override
    public View findViews(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.fragment_more, container, false);
    }

    @Override
    public void initViews() {
        Picasso.with(getContext()).load(R.drawable.default_user).transform(new CircleTransform()).into(imageHead);
        //初始化积分墙
        OffersManager.getInstance(getActivity()).onAppLaunch();
//        OffersBrowserConfig.getInstance(getActivity()).setBrowserTitleBackgroundColor(R.color.colorMain);
        OffersBrowserConfig.getInstance(getActivity()).setLogoVisibility(false);
        OffersBrowserConfig.getInstance(getActivity()).setBrowserTitleText("做任务");
        //积分变动通知
        PointsManager.getInstance(getActivity()).registerNotify(pointsChangeNotify);
        //积分到账通知
        PointsManager.getInstance(getActivity()).registerPointsEarnNotify(pointsEarnNotify);

        txtScore.setText(String.format("%s U币", PointsManager.getInstance(getActivity()).queryPoints()));
    }

    @Override
    public void loadData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        user = BmobUser.getCurrentUser(User.class);
        if (null != user) {
            txtUserName.setText(user.getUsername());
            txtSign.setText(TextUtils.isEmpty(user.getSign()) ? "编辑个性签名" : user.getSign());
            if (null != user.getIcon()) {
                LogUtil.e(TAG, "getFileUrl=" + user.getIcon().getFileUrl());
                LogUtil.e(TAG, "getUrl=" + user.getIcon().getUrl());
                LogUtil.e(TAG, "getFilename=" + user.getIcon().getFilename());
                Picasso.with(getContext()).load(user.getIcon().getFileUrl())
                        .placeholder(R.drawable.default_user).transform(new CircleTransform()).into(imageHead);
            }
            if ("女".equals(user.getSex())) {
                Picasso.with(getContext()).load(R.drawable.ic_girl).into(imageSex);
            } else
                Picasso.with(getContext()).load(R.drawable.ic_boy).into(imageSex);
        }
    }

    @OnClick({R.id.txt_fav, R.id.txt_share, R.id.txt_comment, R.id.txt_username, R.id.txt_exit,
            R.id.line_edit, R.id.image_setting, R.id.line_score})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.txt_fav:
                Intent intent = new Intent();
                intent.setClass(getActivity(), CollecActivity.class);
                intent.putExtra("title", "我的收藏");
                startActivity(intent);
                break;
            case R.id.txt_share:
                showShare();
                break;
            case R.id.txt_comment:
                goToMarket(getActivity(), "com.moqianfan.mcuassistant");
                break;
            case R.id.txt_username:
                if (null == user) {
                    openActivity(LoginActivity.class);
                    getActivity().finish();
                }
                break;
            case R.id.txt_exit:
                if (null != user) {
                    MobclickAgent.onProfileSignOff();
                    BmobUser.logOut();//清除缓存的用户数据
                }
                openActivity(LoginActivity.class);
                getActivity().finish();
                break;
            case R.id.line_edit:
                if (null == user)
                    showToastShort("请先登陆");
                else
                    showSetSign(view);
                break;
            case R.id.image_setting:
                if (null == user) {
                    openActivity(LoginActivity.class);
                    getActivity().finish();
                } else {
                    openActivity(UserInfoActivity.class);
                }
                break;
            case R.id.line_score:
                OffersManager.getInstance(getActivity()).showOffersWall();
                break;
        }
    }

    private PointsChangeNotify pointsChangeNotify = new PointsChangeNotify() {
        @Override
        public void onPointBalanceChange(float v) {
            LogUtil.d(TAG, "当前积分=" + v);
            txtScore.setText(String.format("%sU币", v));
            User newUser = new User();
            newUser.setScore((int) v);
            newUser.update(user.getObjectId(), new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (null == e) {
                        LogUtil.e(TAG, "同步成功");
                        user = BmobUser.getCurrentUser(User.class);
                    } else {
                        LogUtil.e(TAG, "同步失败：" + e.toString());
                    }
                }
            });
        }
    };
    //积分到账通知
    private PointsEarnNotify pointsEarnNotify = new PointsEarnNotify() {
        @Override
        public void onPointEarn(Context context, EarnPointsOrderList earnPointsOrderList) {
            if (!earnPointsOrderList.isEmpty()) {
                LogUtil.d(TAG, "积分到账：" + earnPointsOrderList.getCurrencyName());
                LogUtil.d(TAG, "积分到账：" + earnPointsOrderList.get(0).toString());
            }
        }
    };

    private void showSetSign(View parent) {

        LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.view_pop_comm, null);
        TextView title = (TextView) view.findViewById(R.id.txt_pop_title);
        title.setText("个性签名");
        final EditText edit1 = (EditText) view.findViewById(R.id.edit_pop_value1);
        edit1.setHint("请输入签名");
        EditText edit2 = (EditText) view.findViewById(R.id.edit_pop_value2);
        edit2.setVisibility(View.GONE);
        Button btnCalcel = (Button) view.findViewById(R.id.btn_no);
        btnCalcel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != popupWindow && popupWindow.isShowing())
                    popupWindow.dismiss();
            }
        });
        Button btnYes = (Button) view.findViewById(R.id.btn_yes);
        btnYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateSign(edit1.getText().toString());
                if (null != popupWindow && popupWindow.isShowing())
                    popupWindow.dismiss();
            }
        });

        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        // 使其聚集
        popupWindow.setFocusable(true);
        // 设置允许在外点击消失
        popupWindow.setOutsideTouchable(false);

        // 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        // 显示的位置为:屏幕的宽度的一半-PopupWindow的高度的一半
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = 0.6f;
        getActivity().getWindow().setAttributes(lp);
        popupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                lp.alpha = 1f;
                getActivity().getWindow().setAttributes(lp);
            }
        });
    }

    //服务器同步签名数据
    private void updateSign(String sign) {
        User newUser = new User();
        newUser.setSign(sign);
        newUser.update(user.getObjectId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (null == e) {
                    sendMsg("更新成功", 0x123, handler);
                } else {
                    sendMsg("同步服务器失败：" + e.getMessage(), 0x124, handler);
                }
            }
        });
    }

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            switch (msg.what) {
                case 0x123:
                    user = BmobUser.getCurrentUser(User.class);
                    showToastShort(bundle.getString("msg"));
                    txtSign.setText(user.getSign());
                    break;
                case 0x124:
                    showToastLong(bundle.getString("msg"));
                    break;
            }
            return true;
        }
    });

    public static void goToMarket(Context context, String packageName) {
        Uri uri = Uri.parse("market://details?id=" + packageName);
        Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
        try {
            context.startActivity(goToMarket);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void showShare() {
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

        // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle(getString(R.string.app_name));
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl("http://zhushou.360.cn/detail/index/soft_id/2972227");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("天了噜,51单片机学习神器，这么好的软件才发现");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        oks.setImageUrl("http://p18.qhimg.com/t01fb4d30f94b20db23.png");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://p18.qhimg.com/t01fb4d30f94b20db23.png");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
//        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");

        // 启动分享GUI
        oks.show(getActivity());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //销毁积分变动通知
        PointsManager.getInstance(getActivity()).unRegisterNotify(pointsChangeNotify);
        //销毁积分到账通知
        PointsManager.getInstance(getActivity()).unRegisterPointsEarnNotify(pointsEarnNotify);
        //回收积分墙
        OffersManager.getInstance(getActivity()).onAppExit();
    }
}
